<?php
namespace Modules\Frontend\Controllers;

class TradeBusinessBuyController extends \Phalcon\Mvc\Controller {
	public function beforeExecuteRoute() {
		\Components\Utils::isClosedFrontent($this);
	}

	public function initialize() {
		$this -> response -> setStatusCode(200, 'OK') -> sendHeaders() -> setContentType('application/json', 'UTF-8');
	}

	public function freeze() {
		$service = $this -> tradeSecond::getBuyServiceInstance() -> find([
			'conditions' => 'status = 1 AND last_time < ' . (time() - 21600)
		]);

		if($service['code'] != 0) {
			return false;
		}

		foreach($service['trade_buy'] as $trade_buy) {
			$this -> db -> begin();
			try {
				$serviceUser = $this -> account::getServiceInstance() -> findFirstById($trade_buy -> from_user_id);
				$serviceUser['user'] -> status = 2;
				if(!$serviceUser['user'] -> save())  { throw new \Exception('取消失败'); }

				$findFirstTradeSell = $this -> tradeSecond::getSellServiceInstance() -> findFirstById($trade_buy -> trade_sell_id);
				if($findFirstTradeSell['code'] == 0) {
					$findFirstTradeSell['trade_sell'] -> trade_buy_id = 0;
					$findFirstTradeSell['trade_sell'] -> to_user_id = 0;
					$findFirstTradeSell['trade_sell'] -> status = 0;
					if(!$findFirstTradeSell['trade_sell'] -> save())  { throw new \Exception('取消失败'); }
				}

				$trade_buy -> trade_sell_id = 0;
				$trade_buy -> to_user_id = 0;
				$trade_buy -> status = 5;
				if(!$trade_buy -> save())  { throw new \Exception('取消失败'); }

				$this -> db -> commit();
			} catch(\Exception $e) {
				$this -> db -> rollback();

				//return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
			}
		}
	}

	public function indexAction() {
		$serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($serviceUser['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
		}

		$query = $this -> request -> getQuery();
		if(!isset($query['page'])) {
			$query['page'] = 1;
		} else if($query['page'] <= 0)  {
			$query['page'] = 1;
		} else {
			$query['page'] = abs($query['page']);
		}

		if(!isset($query['limit'])) {
			$query['limit'] = 10;
		} else if($query['limit'] <= 0)  {
			$query['limit'] = 10;
		} else {
			$query['limit'] = abs($query['limit']);
		}

		$this -> freeze();

		$service = $this -> tradeSecond::getBuyServiceInstance() -> pager([
			'conditions' => 'from_user_id = ' . $serviceUser['user'] -> user_id,
			'order' => 'status ASC,create_time DESC'
		], $query['limit'], $query['page']);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'pager' => $service['pager']]);
	}

	public function findFirstByIdAction($id) {
		$serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($serviceUser['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
		}

		$serviceBuy = $this -> tradeSecond::getBuyServiceInstance() -> findFirstById($id);
		if($serviceBuy['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceBuy['code'],'msg'=>'进货订单获取失败']);
		}
		/*
		if($serviceBuy['trade_buy'] -> status != 1) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'进货订单已打款']);
		}
		*/

		$serviceSell = $this -> tradeSecond::getSellServiceInstance() -> findFirstById($serviceBuy['trade_buy'] -> trade_sell_id);
		if($serviceSell['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceSell['code'],'msg'=>'销售订单获取失败']);
		}
		/*
		if($serviceSell['trade_sell'] -> status != 2) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'销售订单已确认打款']);
		}
		*/

		$serviceUserSell = $this -> account::getServiceInstance() -> findFirstById($serviceSell['trade_sell'] -> from_user_id);
		if($serviceUserSell['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUserSell['code'],'msg'=>$serviceUserSell['message']]);
		}
		if($serviceUserSell['user'] -> pid <= 0) {
			$serviceParentUserSell['user'] = [
				'cellphone' => '无推荐人'
			];
		} else {
			$serviceParentUserSell = $this -> account::getServiceInstance() -> findFirstById($serviceUserSell['user'] -> pid);
			if($serviceParentUserSell['code'] != 0) {
				$serviceParentUserSell['user'] = [
					'cellphone' => '无推荐人'
				];
			}
		}

		$serviceBankInfo = $this -> account::getBankInfoServiceInstance() -> findFirstById($serviceSell['trade_sell'] -> user_bank_info_id);
		if($serviceBankInfo['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceBankInfo['code'],'msg'=>'银行卡信息获取失败']);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'user_sell' =>$serviceUserSell['user'],'parent_user_sell'=>$serviceParentUserSell['user'], 'trade_buy' => $serviceBuy['trade_buy'],'trade_sell'=>$serviceSell['trade_sell'],'user_bank_info' => $serviceBankInfo['user_bank_info']]);
	}

	public function statusAction($id, $status) {
		$serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($serviceUser['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
		}

		$post = $this -> request -> getPost();
		if(!$this -> security -> checkHash($post['safePassword'], $serviceUser['user'] -> safe_password)) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'安全密码错误']);
		}

		$serviceBuy = $this -> tradeSecond::getBuyServiceInstance() -> findFirstById($id);
		if($serviceBuy['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceBuy['code'],'msg'=>'进货订单获取失败']);
		}
		if($serviceBuy['trade_buy'] -> status != 1) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'进货订单已打款']);
		}

		$serviceSell = $this -> tradeSecond::getSellServiceInstance() -> findFirstById($serviceBuy['trade_buy'] -> trade_sell_id);
		if($serviceSell['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceSell['code'],'msg'=>'销售订单获取失败']);
		}
		if($serviceSell['trade_sell'] -> status != 2) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'销售订单已确认打款']);
		}

		$serviceBuy['trade_buy'] -> last_time = time();
		$serviceSell['trade_sell'] -> last_time = $serviceBuy['trade_buy'] -> last_time;

		switch($status) {
			case 3:
			case '3':
				if(isset($post['imageContent']) && !empty($post['imageContent'])) {
					$saveFileName = date('Y').'/'.date('m').'/'.date('d');
					$path = PUBLIC_PACH . 'u/'.$saveFileName;
					$saveImage = \Components\Utils::base64_image_content($post['imageContent'], $path);
					if($saveImage['code'] != 0) {
						
					} else {
						$saveFileName .= '/'.$saveImage['file_name'];
						$serviceBuy['trade_buy'] -> image = $saveFileName;
					}
				}

				$serviceBuy['trade_buy'] -> status = 3;
				$serviceSell['trade_sell'] -> status = 3;
				break;
		}

		$this -> db -> begin();
		try {
			if(!$serviceBuy['trade_buy'] -> save()) {
				throw new \Exception('确认失败');
			}
			if(!$serviceSell['trade_sell'] -> save()) {
				throw new \Exception('确认失败');
			}

			$this -> db -> commit();
		} catch(\Exception $e) {
			$this -> db -> rollback();

			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'确认成功']);
	}

	public function createAction() {
		$post = $this -> request -> getPost();

		if($post['amount'] <= 0) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'数量不能少于0']); }

		if(($post['amount'] % 1000) != 0) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'数量输入有误']); }

		$serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($serviceUser['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]); }

		if(!$this -> security -> checkHash($post['safePassword'], $serviceUser['user'] -> safe_password)) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'安全密码错误']);
		}

		switch($serviceUser['user'] -> level) {
			case 1:
				if($post['amount'] > 5000) {
					return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'输入数量大于指定数量']);
				}
				break;
			case 2:
				if($post['amount'] > 10000) {
					return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'输入数量大于指定数量']);
				}
				break;
			case 3:
			case 4:
				if($post['amount'] > 20000) {
					return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'输入数量大于指定数量']);
				}
				break;
		}

		$serviceUserWallet = $this -> account::getWalletServiceInstance() -> findFirstById($serviceUser['user'] -> user_id);
		if($serviceUserWallet['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUserWallet['code'],'msg'=>$serviceUserWallet['message']]);
		}

		if($post['amount'] < 10000) {
			$priceTrade = 1;
		} else if($post['amount'] >= 10000) {
			$priceTrade = 2;
		} else {
			$priceTrade = 0;
		}
		if($serviceUserWallet['user_wallet'] -> price_trade < $priceTrade) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'交易票不足']);
		}

		$findTradeBuy = $this -> tradeSecond::getBuyServiceInstance() -> find([
			'conditions' => 'from_user_id = ' . $serviceUser['user'] -> user_id,
			'order' => 'trade_buy_id DESC',
			'limit' => 10
		]);
		$profit = 0;
		if($findTradeBuy['code'] != 0) {
			if($post['amount'] < 2000) {
				return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'首次进单不能少于2000']);
			}
			if($post['amount'] > 3000) {
				return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'首次进单不能大于3000']);
			}

			if($post['amount'] < 5000) {
				$profit = 11;
			} else if($post['amount'] < 10000) {
				$profit = 10;
			} else if($post['amount'] >= 10000) {
				$profit = 8;
			}
		} else {
			$tradeBuyFirst = $findTradeBuy['trade_buy'] -> getFirst();
			if($tradeBuyFirst -> status != 6) {
				return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'请等候上一单匹配完成']);
			}

			if($tradeBuyFirst -> amount > $post['amount']) {
				return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'数量不能少于上次的'.$tradeBuyFirst -> amount]);
			}

			$countTradeBuy = $findTradeBuy['trade_buy'] -> count();
			switch($countTradeBuy) {
				case 1:
					if($post['amount'] > 5000) {
						return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'二次进单不能大于5000']);
					}
					break;
				case 2:
					if($post['amount'] > 10000) {
						return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'三次进单不能大于10000']);
					}
					break;
				default:
					if($post['amount'] > 20000) {
						return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'进单不能大于20000']);
					}
					break;
			}

			if($tradeBuyFirst -> amount < 5000) {
				if($post['amount'] >= 5000) {
					$profit = 10;
				} else {
					$profit = 16;
				}
			} else if($tradeBuyFirst -> amount < 10000) {
				if($post['amount'] >= 10000) {
					$profit = 8;
				} else {
					$profit = 15;
				}
			} else if($tradeBuyFirst -> amount >= 10000) {
				$profit = 13;
			}
		}

		$this -> db -> begin();
		try {
			$serviceTrade = $this -> account::getWalletServiceInstance() -> updateDecAmount(['type'=>4,'amount'=>$priceTrade,'user_id'=>$serviceUser['user'] -> user_id]);
			if($serviceTrade['code'] != 0) { throw new \Exception($serviceTrade['message']); }
			//if($serviceTrade['code'] != 0) { throw new \Exception('进货失败'); }

			$createTrade = $this -> tradeSecond::getBuyServiceInstance() -> create([
				'trade_sell_id' => 0,
				'from_user_id' => $serviceUser['user'] -> user_id,
				'to_user_id' => 0,
				'profit' => $profit,
				'amount' => $post['amount'],
				'original_amount' => $post['amount'],
				'loop_number' => 1,
				'create_time' => time(),
				'last_time' => time(),
				'status' => 0,
			]);
			if($createTrade['code'] != 0) {
				throw new \Exception($createTrade['message']);
			}

			$this -> db -> commit();
		} catch(\Exception $e) {
			$this -> db -> rollback();

			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'进货成功']);
	}
}